export function initBannerSlider(bannerId) {
  // 常量定义
  const ELASTIC_RANGE = 300;
  const ELASTIC_FACTOR = 0.3;
  const ANIMATION_DURATION = 300;
  const ACTIVE_LINK_TIMEOUT = 200;

  const banner = document.getElementById(bannerId);
  if (!banner) {
    console.error(`Element with ID "${bannerId}" not found.`);
    return;
  }

  let isDragging = false;
  let startPosX = 0;
  let currentTranslate = 0;
  let prevTranslate = 0;
  let animationId = null;
  let activeAdom = null;
  let resizeTimeoutId = null;

  // 初始化 transform 样式
  banner.style.transform = `translateX(${currentTranslate}px)`;

  // 获取边界值
  function getBoundaries() {
    const container = banner.parentElement;
    if (!container) {
      console.warn('Banner container not found');
      return { min: 0, max: 0 };
    }
    
    const containerWidth = container.offsetWidth;
    const trackWidth = banner.scrollWidth;
    return {
      min: containerWidth - trackWidth, // 确保 min 值正确
      max: 0
    };
  }

  // 拖拽开始
  function dragStart(e) {
    if (e.type === 'mousedown' && e.button !== 0) return;
    isDragging = true;
    startPosX = e.clientX || e.touches[0].clientX;
    banner.classList.add('dragging');
    
    if (e.target.tagName === 'A') {
      activeAdom = e.target;
      setTimeout(() => {
        if (activeAdom) {
          activeAdom.classList.add('pointer-events-none');
        }
      }, ACTIVE_LINK_TIMEOUT);
    }
    
    cancelAnimationFrame(animationId);
  }

  // 拖拽中
  function drag(e) {
    if (!isDragging) return;
    
    const currentPosX = e.clientX || e.touches[0].clientX;
    const diff = currentPosX - startPosX;
    const { min } = getBoundaries();
    
    // 弹性边界处理
    let newTranslate = prevTranslate + diff;
    if (newTranslate > 0) {
      // 右边界弹性
      const overshoot = Math.min(newTranslate, ELASTIC_RANGE);
      newTranslate = overshoot * ELASTIC_FACTOR;
    } else if (newTranslate < min) {
      // 左边界弹性
      const overshoot = Math.min(min - newTranslate, ELASTIC_RANGE);
      newTranslate = min - overshoot * ELASTIC_FACTOR;
    }
    
    currentTranslate = newTranslate;
    
    // 只有当实际产生了位移时才防止页面滚动，避免显示禁止拖动图标
    if (Math.abs(diff) > 5) {
      e.preventDefault();
    }
    
    // 使用requestAnimationFrame优化性能
    if (!animationId) {
      animationId = requestAnimationFrame(() => {
        banner.style.transform = `translateX(${currentTranslate}px)`;
        animationId = null;
      });
    }
  }

  // 拖拽结束
  function dragEnd() {
    if (!isDragging) return;
    isDragging = false;
    
    if (activeAdom) {
      activeAdom.classList.remove('pointer-events-none');
      activeAdom = null;
    }
    
    banner.classList.remove('dragging');
    const { min } = getBoundaries();
    
    if (currentTranslate > 0 || currentTranslate < min) {
      // 回弹到边界
      const target = currentTranslate > 0 ? 0 : min;
      animateTo(target);
    } else {
      prevTranslate = currentTranslate;
    }
  }

  // 平滑回弹动画
  function animateTo(target) {
    const startTime = performance.now();
    const startPos = currentTranslate;
    function step(currentTime) {
      const elapsed = currentTime - startTime;
      const progress = Math.min(elapsed / ANIMATION_DURATION, 1);
      const easeProgress = 0.5 * (1 - Math.cos(progress * Math.PI));

      currentTranslate = startPos + (target - startPos) * easeProgress;
      banner.style.transform = `translateX(${currentTranslate}px)`;

      if (progress < 1) {
        animationId = requestAnimationFrame(step);
      } else {
        currentTranslate = target;
        prevTranslate = target;
        animationId = null;
      }
    }

    animationId = requestAnimationFrame(step);
  }

  // 窗口大小变化处理（带防抖）
  function handleResize() {
    clearTimeout(resizeTimeoutId);
    resizeTimeoutId = setTimeout(() => {
      const { min } = getBoundaries();
      currentTranslate = Math.max(min, Math.min(0, currentTranslate));
      prevTranslate = currentTranslate;
      banner.style.transform = `translateX(${currentTranslate}px)`;
    }, 100); // 100ms防抖延迟
  }

  // 按下鼠标或触摸开始拖拽
  banner.addEventListener('pointerdown', dragStart);
  // 拖动中
  banner.addEventListener('pointermove', drag);
  // 松开鼠标或触摸结束拖拽
  banner.addEventListener('pointerup', dragEnd);
  // 取消拖拽（例如触摸操作在元素外释放）
  banner.addEventListener('pointercancel', dragEnd);
  // 鼠标离开元素时结束拖拽
  banner.addEventListener('pointerleave', dragEnd);
  // 窗口大小变化时处理
  window.addEventListener('resize', handleResize);

  // 返回清理函数，用于在组件卸载时移除事件监听器
  return function cleanup() {
    banner.removeEventListener('pointerdown', dragStart);
    banner.removeEventListener('pointermove', drag);
    banner.removeEventListener('pointerup', dragEnd);
    banner.removeEventListener('pointercancel', dragEnd);
    banner.addEventListener('mouseleave', dragEnd);
    window.removeEventListener('resize', handleResize);

    
    // 清理动画和定时器
    if (animationId) {
      cancelAnimationFrame(animationId);
      animationId = null;
    }
    
    if (resizeTimeoutId) {
      clearTimeout(resizeTimeoutId);
      resizeTimeoutId = null;
    }
    
    // 清理activeAdom状态
    if (activeAdom) {
      activeAdom.classList.remove('pointer-events-none');
      activeAdom = null;
    }
  };
}